﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using viNews.Classes;
using viNews.Controllers;
using visinia.SmartEngine;

public partial class Admin_Pages_viNews_News_NewsEditor : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebPageController.AddScriptLink(Page, WebRoots.GetAdminPagesRoot + "viNews/News/Editor.js");
        WebPageController.AddCssLink(Page, WebRoots.GetAdminPagesRoot + "viNews/News/EditorStyle.css");
        if (!IsPostBack)
        {
            List<Tag> tags = TagController.GetTags();            
            foreach (Tag tag in tags)
            {
                HtmlAnchor a = new HtmlAnchor();
                a.InnerText = tag.Name;                
                TagsList.Controls.Add(a);
            }
            AUTHORS.DataSource = Membership.GetAllUsers();
            AUTHORS.DataBind();            
            //create a new entry
            if (Request.QueryString["NewsId"] == null)
            {
                DATE.Text = DateTime.Now.ToString();
                PUBLISH.Checked = true;
                hNewsId.Value = "0";
            }
            else
            {
                // edit an already existing news
                int NewsId = Convert.ToInt32(Request.QueryString["NewsId"]);
                hNewsId.Value = NewsId.ToString();
                News news = NewsController.GetNews(NewsId, false);
                TITLE.Text = news.Title;
                DATE.Text = news.Date.ToString();
                if (string.IsNullOrEmpty(news.Url))//this news's category is deleted
                {
                    CATEGORY.Control.Items.Insert(0, "< No Category >");
                    CATEGORY.Control.SelectedIndex = 0;
                }
                else
                {
                    URL.Visible = true;
                    URL.Value = news.Url;
                    CATEGORY.CategoryId = news.Category;
                }
                if (!string.IsNullOrEmpty(news.ImageUrl))
                {
                    NewsImageAttachmentUrl.Value = news.ImageUrl;                                        
                    HtmlGenericControl img = new HtmlGenericControl("img");
                    img.Attributes["src"] = WebRoots.GetResourcesRoot + news.ImageUrl;
                    NewsImageAttachmentPreview.Controls.Add(img);
                }
                SUMMARY.Text = news.Summary;
                PUBLISH.Checked = news.Publish;
                DESCRIPTION.Text = NewsController.GetNewsDescription(NewsId, false);

                List<Tag> newstags = TagController.GetTags(NewsId);
                if (newstags != null)
                {
                    foreach (Tag newstag in newstags)
                    {
                        NewsTags.Value += newstag.Name + ',';                        
                    }
                }                
            }
        }
    }

    protected void SAVE_Click(object sender, EventArgs e)
    {
        //save a new news
        if (Request.QueryString["NewsId"] == null)
        {
            AddNews();
        }
        else
        {// update an already existing news           
            int newsid = 0;
            if (!Int32.TryParse(Request.QueryString["NewsId"], out newsid))
                return;
            News news = NewsController.GetNews(newsid, false);
            if (news == null)
                return;
            news.Title = TITLE.Text;
            news.Author = AUTHORS.SelectedValue;
            news.Date = Convert.ToDateTime(DATE.Text);
            if (CATEGORY.Control.Text != "< No Category >")
                news.Category = CATEGORY.CategoryId;
            news.Url = RemoveIllegalCharacters(news.Title);
            news.ImageUrl = NewsImageAttachmentUrl.Value;            
            news.Summary = SUMMARY.Text;
            news.Publish = PUBLISH.Checked;
            NewsController.UpdateNews(news, DESCRIPTION.Text);
                        
            //tags
            TagController.ResetTags(newsid);                        
            string[] selectedtags = NewsTags.Value.Split(',');
            foreach (string tagName in selectedtags)
            {
                if (string.IsNullOrEmpty(tagName.Trim()))
                    continue;
                Tag existingTag = TagController.GetTag(tagName);
                if(existingTag != null)
                {
                    if( ! TagController.GetTags(news.NewsId).Exists(p=> p.TagId == existingTag.TagId))
                        TagController.InsertTag(existingTag.TagId, news.NewsId);
                }
                else
                {
                    int id = TagController.AddTag(new Tag(tagName));
                    TagController.InsertTag(id, news.NewsId);
                }
            }
        }
        Response.Redirect(Request.RawUrl);
    }

    bool Exist(string[] values, string find)
    {
        foreach (string value in values)
        {
            if (value.Trim().CompareTo(find) == 0)
                return true;
        }
        return false;
    }

    private void AddNews()
    {
        News news = new News();
        news.Title = TITLE.Text;
        news.Author = AUTHORS.SelectedValue;
        news.Date = Convert.ToDateTime(DATE.Text);
        news.Category = CATEGORY.CategoryId;
        news.Url = RemoveIllegalCharacters(news.Title);
        news.ImageUrl = NewsImageAttachmentUrl.Value;        
        news.Summary = SUMMARY.Text;
        news.Publish = PUBLISH.Checked;
        int newsid = NewsController.AddNews(news, DESCRIPTION.Text);
        //tags
        TagController.ResetTags(newsid);
        string[] selectedtags = NewsTags.Value.Split(',');
        foreach (string tagName in selectedtags)
        {
            if (string.IsNullOrEmpty(tagName.Trim()))
                continue;
            Tag existingTag = TagController.GetTag(tagName);
            if (existingTag != null)
            {
                TagController.InsertTag(existingTag.TagId, newsid);
            }
            else
            {
                int id = TagController.AddTag(new Tag(tagName));
                TagController.InsertTag(id, newsid);
            }
        }
        // reload the newly created news
        Response.Redirect(SystemMenu.CallPage("viNews", "EditNews", "NewsId", newsid.ToString()));        
    }

    protected void CANCEL_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.RawUrl);
    }
    
    private static string RemoveIllegalCharacters(string Title)
    {
        if (string.IsNullOrEmpty(Title))
            return Title;

        Title = Title.Replace(":", string.Empty);
        Title = Title.Replace("/", string.Empty);
        Title = Title.Replace("?", string.Empty);
        Title = Title.Replace("#", string.Empty);
        Title = Title.Replace("[", string.Empty);
        Title = Title.Replace("]", string.Empty);
        Title = Title.Replace("@", string.Empty);
        Title = Title.Replace("*", string.Empty);
        Title = Title.Replace(".", string.Empty);
        Title = Title.Replace(",", string.Empty);
        Title = Title.Replace("\"", string.Empty);
        Title = Title.Replace("&", string.Empty);
        Title = Title.Replace("'", string.Empty);
        Title = Title.Replace(" ", "-");
        return HttpUtility.UrlEncode(Title).Replace("%", string.Empty);
    }
}
